package com.cy.springcloudalibaba.services.impls;

import com.cy.springcloudalibaba.mappers.ProductMapper;
import com.cy.springcloudalibaba.models.Product;
import com.cy.springcloudalibaba.services.ProductService;
import io.seata.core.context.RootContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Description: 商品
 * @ClassName: ProductServiceImpl
 * @Author: chenyu
 * @Date: 2025/2/6 10:53
 */
@Slf4j
@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductMapper productMapper;

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW) //开启新事务
    public Product reduceStock(Integer productId, Integer amount) throws Exception {
        log.info("[checkStock] 当前XID: {}", RootContext.getXID());
        //检查库存
        log.info("[checkStock] 检查 {} 库存", productId);
        Product product = productMapper.selectByPrimaryKey(productId);

        if (product.getStock() < amount) {
            log.warn("[checkStock] {} 库存不足，当前库存：{}", productId, product.getStock());
            throw new Exception("库存不足");
        }

        log.info("[reduceStock] 开始扣减 {} 库存", productId);
        //扣减库存
        int updateCount = productMapper.reduceStock(productId, amount);

        if (updateCount == 0) {
            log.warn("[reduceStock] 扣减 {} 库存失败", productId);
            throw new Exception("库存不足");
        }
        log.info("[reduceStock] 扣除 {} 库存成功", productId);

        return product;
    }
}
